package leetCode;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/
 */
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = {-1, -1};
        if(nums.length == 0) return ret;
        int left = 0, right = nums.length - 1;
        //找左端点
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        if(nums[left] != target) return ret;
        ret[0] = left;
        //找右端点
        left = 0;
        right = nums.length - 1;
        while(left < right) {
            int mid = left + (right - left + 1) / 2;
            if(nums[mid] > target) right = mid - 1;
            else left = mid;
        }
        ret[1] = right;
        return ret;
    }
}